<template>
  <el-upload
    :action="''"
    :on-change="handleChange"
    :on-remove="handleRemove"
    :file-list="fileList"
    :auto-upload="false"
    :on-preview="handlePictureCardPreview"
    list-type="picture-card"
    ref="uploadRef"
    :multiple="props.multiple"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>

  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, defineProps, defineEmits, onMounted, defineExpose } from 'vue';
import { ElMessage } from 'element-plus';
import type { UploadProps } from 'element-plus';
import { ipfsClient } from '@/api/IPFSClient';
import { config } from '@/config/config';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => []
  },
  multiple: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:modelValue']);

const fileList = ref([]);
const uploadRef = ref(null);

// 监听 v-model 变化
watch(() => props.modelValue, (newVal) => {
  fileList.value = newVal.map(file => ({ name: file.name, url: file.url }));
});

// 处理文件变化
const handleChange = async (file) => {
  try {
    const result = await ipfsClient.add(file.raw);
    const ipfsUrl = `${config.ipfs_gateway}${result.path}`;
    const newFile = { name: file.name, url: ipfsUrl };
    if(props.multiple){
        emit('update:modelValue', [...props.modelValue, newFile]);
    }else{
        emit('update:modelValue', [newFile]);
    }
  } catch (error) {
    ElMessage.error(t('uploadFailed'));
    console.error(error);
  }
};

// 处理文件移除
const handleRemove = (file) => {
  const index = props.modelValue.findIndex(f => f.name === file.name);
  if (index !== -1) {
    const newModelValue = props.modelValue.filter((_, i) => i !== index);
    emit('update:modelValue', newModelValue);
  }
};

// 预览
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
}

// 清空文件列表
const clearFiles = () => {
  uploadRef.value.clearFiles();
};

onMounted(() => {
  // 初始化文件列表
  fileList.value = props.modelValue.map(file => ({ name: file.name, url: file.url }));
});

// 暴露方法给父组件
defineExpose({ clearFiles });
</script>

<style scoped>
</style>